package br.com.reparoja.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.reparoja.entities.Brand;
import br.com.reparoja.entities.Equipment;
import br.com.reparoja.entities.User;
import br.com.reparoja.persistence.Factory;
import br.com.reparoja.persistence.Utils;

public class ListServlet<T> extends HttpServlet {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public void service(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		try {
			String ret = "";
			String entity = req.getParameter("e");

			if (entity == null)
				entity = req.getParameter("entity");

			if (entity == null) {
				resp.getWriter().println("[\"not found\"]");
				return;
			}

			if (entity.equalsIgnoreCase(User.class.getSimpleName())) {
				ret = list(User.class);
			}
			else if (entity.equalsIgnoreCase(Equipment.class.getSimpleName())) {
				ret = list(Equipment.class);
			}
			else if (entity.equalsIgnoreCase(Brand.class.getSimpleName())) {
				ret = list(Brand.class);
			}

			resp.setContentType("text/plain");
			resp.getWriter().println(ret);
		} catch (Exception e) {
			StringBuilder sb = new StringBuilder();
			sb.append("[");

			sb.append("{");
			sb.append("\"id\": ").append(-1).append(", ");
			sb.append("\"name\": \"").append(e.getMessage()).append("\"");
			sb.append("}, ");

			StackTraceElement[] stack = e.getStackTrace();

			for (StackTraceElement stackTraceElement : stack) {
				sb.append("{");
				sb.append("\"id\": ").append(0).append(", ");
				sb.append("\"name\": \"").append(stackTraceElement.toString())
						.append("\"");
				sb.append("}, ");

			}

			sb.setLength(sb.length() - 2);
			sb.append("]");

			resp.getWriter().println(sb.toString());
		}

	}

	private <T> String list(Class<T> klass) {
		EntityManager em = Factory.get().createEntityManager();
		TypedQuery<T> consulta = em.createQuery("FROM " + klass.getSimpleName(), klass);
		List<T> result = consulta.getResultList();
		String out = Utils.toJSON(result);
		em.close();
	
		return /*klass.getSimpleName() + " " + result.size() + " " +*/ out;
	}
}
